using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using System.Xml;

namespace WIT.Global;

/// <summary>
/// service post/get帮助类
/// </summary>
public class ServiceHelper
{
	/// <summary>
	/// webservice post
	/// </summary>
	/// <param name="url">接口地址</param>
	/// <param name="paramDic">参数集合（key:value）</param>
	/// <param name="headers">指定SOAPHeader验证</param>
	/// <param name="method">如果指定方法，则自动拼接到url中</param>
	/// <returns></returns>
	public static string WebServicePost(string url, Dictionary<string, object> paramDic, WebHeaderCollection headers = null, string method = "")
	{
		byte[] array = null;
		Stream stream = null;
		HttpWebRequest httpWebRequest = null;
		HttpWebResponse httpWebResponse = null;
		StringBuilder stringBuilder = new StringBuilder();
		int num = 0;
		foreach (KeyValuePair<string, object> item in paramDic)
		{
			if (num++ > 0)
			{
				stringBuilder.Append("&");
			}
			stringBuilder.Append($"{item.Key}={item.Value}");
		}
		array = Encoding.UTF8.GetBytes(stringBuilder.ToString());
		if (!string.IsNullOrEmpty(method))
		{
			url = url + "/" + method;
		}
		httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
		httpWebRequest.Method = "post";
		if (headers != null)
		{
			httpWebRequest.Headers = headers;
		}
		httpWebRequest.ContentType = "application/x-www-form-urlencoded";
		httpWebRequest.ContentLength = array.Length;
		try
		{
			stream = httpWebRequest.GetRequestStream();
		}
		catch (Exception ex)
		{
			return ex.Message;
		}
		stream.Write(array, 0, array.Length);
		stream.Close();
		try
		{
			httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
		}
		catch (WebException ex2)
		{
			return ex2.Message;
		}
		Stream responseStream = httpWebResponse.GetResponseStream();
		XmlTextReader xmlTextReader = new XmlTextReader(responseStream);
		xmlTextReader.MoveToContent();
		string result = xmlTextReader.ReadInnerXml();
		httpWebResponse.Dispose();
		httpWebResponse.Close();
		xmlTextReader.Dispose();
		xmlTextReader.Close();
		responseStream.Dispose();
		responseStream.Close();
		return result;
	}

	/// <summary>
	/// http post (form-data/x-www-form-urlencoded)
	/// </summary>
	/// <param name="url">接口地址</param>
	/// <param name="paramDic">参数集合（key:value）</param>
	/// <param name="headers">指定SOAPHeader验证</param>
	/// <param name="method">如果指定方法，则自动拼接到url中</param>
	/// <returns></returns>
	public static string HttpPost(string url, Dictionary<string, object> paramDic, WebHeaderCollection headers = null, string method = "")
	{
		byte[] array = null;
		Stream stream = null;
		HttpWebRequest httpWebRequest = null;
		HttpWebResponse httpWebResponse = null;
		StringBuilder stringBuilder = new StringBuilder();
		int num = 0;
		foreach (KeyValuePair<string, object> item in paramDic)
		{
			if (num++ > 0)
			{
				stringBuilder.Append("&");
			}
			stringBuilder.Append($"{item.Key}={item.Value}");
		}
		array = Encoding.UTF8.GetBytes(stringBuilder.ToString());
		if (!string.IsNullOrEmpty(method))
		{
			url = url + "/" + method;
		}
		httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
		httpWebRequest.Method = "post";
		if (headers != null)
		{
			httpWebRequest.Headers = headers;
		}
		httpWebRequest.ContentType = "application/x-www-form-urlencoded";
		httpWebRequest.ContentLength = array.Length;
		try
		{
			stream = httpWebRequest.GetRequestStream();
		}
		catch (Exception ex)
		{
			return ex.Message;
		}
		stream.Write(array, 0, array.Length);
		stream.Close();
		try
		{
			httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
		}
		catch (WebException ex2)
		{
			return ex2.Message;
		}
		string result = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8).ReadToEnd();
		httpWebResponse.Dispose();
		httpWebResponse.Close();
		return result;
	}

	/// <summary>
	/// http post (raw)
	/// </summary>
	/// <param name="url">接口地址</param>
	/// <param name="data">传递的数据</param>
	/// <param name="headers">指定SOAPHeader验证</param>
	/// <returns></returns>
	public static string HttpPostRaw(string url, string data, WebHeaderCollection headers = null)
	{
		try
		{
			HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
			httpWebRequest.Method = "post";
			httpWebRequest.ContentType = "application/json";
			if (headers != null)
			{
				httpWebRequest.Headers = headers;
			}
			Stream requestStream = httpWebRequest.GetRequestStream();
			byte[] bytes = Encoding.UTF8.GetBytes(data);
			requestStream.Write(bytes, 0, bytes.Length);
			requestStream.Flush();
			requestStream.Close();
			HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
			string result = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8).ReadToEnd();
			httpWebResponse.Close();
			return result;
		}
		catch (Exception ex)
		{
			return ex.Message;
		}
	}

	/// <summary>
	/// http post (upload files)
	/// </summary>
	/// <param name="url">接口地址</param>
	/// <param name="paramDic">参数集合（key:value）</param>
	/// <param name="fileDic">文件集合(key:fileName)</param>
	/// <param name="headers">指定SOAPHeader验证</param>
	/// <param name="cookies"></param>
	/// <param name="contenttype"></param>
	/// <returns></returns>
	public static string HttpPostFile(string url, Dictionary<string, object> paramDic, Dictionary<string, HttpPostedFileBase> fileDic, WebHeaderCollection headers = null, CookieContainer cookies = null, string contenttype = "multipart/form-data")
	{
		try
		{
			Uri requestUri = new Uri(url);
			string text = "----------" + DateTime.Now.Ticks.ToString("x");
			HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
			httpWebRequest.Headers = headers;
			if (cookies != null)
			{
				httpWebRequest.CookieContainer = cookies;
			}
			httpWebRequest.ContentType = "multipart/form-data; boundary=" + text;
			httpWebRequest.Method = "POST";
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("--");
			stringBuilder.Append(text);
			stringBuilder.Append("\r\n");
			stringBuilder.Append("Content-Disposition: form-data;");
			foreach (string key in fileDic.Keys)
			{
				stringBuilder.Append("name=\"" + key + "\"; filename=\"" + fileDic[key].FileName + "\"");
			}
			stringBuilder.Append("\r\n");
			stringBuilder.Append("Content-Type: ");
			stringBuilder.Append(contenttype);
			stringBuilder.Append("\r\n");
			stringBuilder.Append("\r\n");
			string s = stringBuilder.ToString();
			byte[] bytes = Encoding.UTF8.GetBytes(s);
			byte[] bytes2 = Encoding.ASCII.GetBytes("--" + text + "\r\n");
			byte[] bytes3 = Encoding.ASCII.GetBytes("\r\n");
			long num = bytes.Length;
			foreach (string key2 in fileDic.Keys)
			{
				num += fileDic[key2].InputStream.Length + bytes3.Length;
			}
			if (paramDic != null)
			{
				StringBuilder stringBuilder2 = new StringBuilder();
				foreach (string key3 in paramDic.Keys)
				{
					stringBuilder2.Append("--");
					stringBuilder2.Append(text);
					stringBuilder2.Append("\r\n");
					stringBuilder2.Append("Content-Disposition: form-data; name=\"");
					stringBuilder2.Append(key3);
					stringBuilder2.Append("\"");
					stringBuilder2.Append("\r\n");
					stringBuilder2.Append("\r\n");
					stringBuilder2.Append(paramDic[key3]);
					stringBuilder2.Append("\r\n");
					byte[] bytes4 = Encoding.UTF8.GetBytes(stringBuilder2.ToString());
					num += bytes4.Length;
				}
			}
			num = (httpWebRequest.ContentLength = num + bytes2.Length);
			Stream requestStream = httpWebRequest.GetRequestStream();
			requestStream.Write(bytes, 0, bytes.Length);
			foreach (string key4 in fileDic.Keys)
			{
				byte[] array = new byte[checked((uint)Math.Min(4096, (int)fileDic[key4].InputStream.Length))];
				int num3 = 0;
				while ((num3 = fileDic[key4].InputStream.Read(array, 0, array.Length)) != 0)
				{
					requestStream.Write(array, 0, num3);
				}
				requestStream.Write(bytes3, 0, bytes3.Length);
			}
			if (paramDic != null)
			{
				StringBuilder stringBuilder3 = new StringBuilder();
				foreach (string key5 in paramDic.Keys)
				{
					stringBuilder3.Append("--");
					stringBuilder3.Append(text);
					stringBuilder3.Append("\r\n");
					stringBuilder3.Append("Content-Disposition: form-data; name=\"");
					stringBuilder3.Append(key5);
					stringBuilder3.Append("\"");
					stringBuilder3.Append("\r\n");
					stringBuilder3.Append("\r\n");
					stringBuilder3.Append(paramDic[key5]);
					stringBuilder3.Append("\r\n");
					byte[] bytes5 = Encoding.UTF8.GetBytes(stringBuilder3.ToString());
					requestStream.Write(bytes5, 0, bytes5.Length);
				}
			}
			requestStream.Write(bytes2, 0, bytes2.Length);
			httpWebRequest.Timeout = 3000;
			WebResponse response = httpWebRequest.GetResponse();
			Stream responseStream = response.GetResponseStream();
			StreamReader streamReader = new StreamReader(responseStream);
			string result = streamReader.ReadToEnd();
			requestStream.Close();
			streamReader.Close();
			responseStream.Close();
			response.Close();
			return result;
		}
		catch (Exception ex)
		{
			return ex.Message;
		}
	}
}
